import os
import sys
import json
from datetime import datetime

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# 导入必要的模块
from src.vision.zhipu_vision_analyzer import ZhipuVisionAnalyzer
from src.vision.error_handler import RetryStrategy, ZhipuApiErrorHandler

def find_test_videos(video_dir):
    """查找测试视频文件"""
    video_extensions = ['.mp4', '.avi', '.mov', '.mkv']
    videos = []
    
    for root, dirs, files in os.walk(video_dir):
        for file in files:
            if any(file.lower().endswith(ext) for ext in video_extensions):
                videos.append(os.path.join(root, file))
    
    return videos

def test_error_handling_integration():
    """集成测试：验证错误处理机制在实际场景中的工作情况"""
    print("=== 开始错误处理机制集成测试 ===")
    
    # 1. 查找测试视频
    video_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'sample_videos')
    test_videos = find_test_videos(video_dir)
    
    if not test_videos:
        print(f"警告：在 {video_dir} 目录下未找到测试视频文件")
        # 尝试其他可能的目录
        other_dirs = ['videos', 'test_videos', 'data/videos']
        for dir_name in other_dirs:
            alt_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), dir_name)
            alt_videos = find_test_videos(alt_dir)
            if alt_videos:
                test_videos = alt_videos
                print(f"在 {alt_dir} 目录下找到 {len(alt_videos)} 个视频文件")
                break
    
    print(f"找到 {len(test_videos)} 个测试视频文件")
    
    # 2. 测试场景1: 正常视频分析
    if test_videos:
        print("\n=== 测试场景1: 正常视频分析 ===")
        test_video_path = test_videos[0]
        print(f"使用视频文件: {test_video_path}")
        
        try:
            analyzer = ZhipuVisionAnalyzer()
            video_id = f"test_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
            print(f"开始分析视频 ID: {video_id}")
            
            # 修改重试策略以加快测试
            analyzer.error_handler.retry_strategy = RetryStrategy(
                max_retries=2,      # 减少重试次数加快测试
                base_delay=1.0,     # 减少延迟时间
                max_delay=5.0
            )
            
            result = analyzer.analyze_video(test_video_path, video_id)
            
            print(f"分析结果: {json.dumps(result, ensure_ascii=False, indent=2)}")
            
            if "status" in result:
                print(f"状态: {result['status']}")
            elif "success" in result:
                print(f"成功: {result['success']}")
                
        except Exception as e:
            print(f"异常捕获: {str(e)}")
    
    # 3. 测试场景2: 不存在的视频文件
    print("\n=== 测试场景2: 不存在的视频文件 ===")
    non_existent_video = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'non_existent_video.mp4')
    print(f"测试不存在的文件: {non_existent_video}")
    
    try:
        analyzer = ZhipuVisionAnalyzer()
        video_id = f"test_error_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
        result = analyzer.analyze_video(non_existent_video, video_id)
        
        print(f"错误处理结果: {json.dumps(result, ensure_ascii=False, indent=2)}")
        print(f"状态: {result.get('status', '未知')}")
        print(f"错误信息: {result.get('error_message', '无')}")
        
    except Exception as e:
        print(f"测试失败: 应该捕获异常但未捕获 - {str(e)}")
    
    # 4. 测试场景3: 错误处理器配置验证
    print("\n=== 测试场景3: 错误处理器配置验证 ===")
    analyzer = ZhipuVisionAnalyzer()
    
    print(f"错误处理器类型: {type(analyzer.error_handler).__name__}")
    print(f"最大重试次数: {analyzer.error_handler.retry_strategy.max_retries}")
    print(f"基础延迟: {analyzer.error_handler.retry_strategy.base_delay}秒")
    print(f"最大延迟: {analyzer.error_handler.retry_strategy.max_delay}秒")
    
    # 验证延迟计算
    delay = analyzer.error_handler.retry_strategy.calculate_delay(1)
    print(f"第1次重试延迟: {delay:.2f}秒")
    
    delay = analyzer.error_handler.retry_strategy.calculate_delay(2)
    print(f"第2次重试延迟: {delay:.2f}秒")
    
    # 5. 测试智谱特定错误类型判断
    print("\n=== 测试场景4: 智谱特定错误类型判断 ===")
    
    test_errors = [
        {"code": 429, "message": "请求频率过高"},
        {"code": 500, "message": "服务器内部错误"},
        {"code": 503, "message": "服务不可用"},
        {"code": 401, "message": "API密钥错误"},
        {"code": 400, "message": "请求参数错误"},
    ]
    
    for error in test_errors:
        should_retry = analyzer.error_handler._should_retry(error)
        action = "应该重试" if should_retry else "不应重试"
        print(f"错误码 {error['code']} ({error['message']}): {action}")
    
    print("\n=== 错误处理机制集成测试完成 ===")
    return True

if __name__ == "__main__":
    test_error_handling_integration()